package com.cmc.cloud.cmclink.doc.controller.admin.special;

import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.mq.MyProducer;
import com.cmc.cloud.cmclink.doc.mq.SiEdiConsumer;
import com.cmc.cloud.cmclink.doc.mq.SiEdiReqVO;
import com.cmc.cloud.cmclink.doc.service.ApplySaveOrUpdateService;
import com.cmc.cloud.cmclink.doc.service.SpecialCargoApplyService;
import com.cmc.cloud.cmclink.doc.service.special.EmailTaskService;
import com.cmc.cloud.cmclink.doc.util.EmailUtil;
import com.cmc.cloud.cmclink.doc.vo.specialcargoapplyvo.*;
import com.cmc.cloud.cmclink.doc.vo.specialcargodgvo.DgByBookingNo;
import com.cmc.cloud.cmclink.system.api.api.file.FileApi;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;
import com.cmes.framework.operatelog.core.annotations.OperateLog;
import com.cmes.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 特种货申请主信息前端接口Controller
 *
 * @author codegen
 */
@Tag(name = "管理后台 - 特种货申请主信息")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL + "/specialCargoApply")
public class SpecialCargoApplyController {

    @Resource
    private SpecialCargoApplyService specialCargoApplyService;
    @Resource
    private ApplySaveOrUpdateService applySaveOrUpdateService;
    @Autowired
    private MyProducer myProducer;
    @Autowired
    private EmailTaskService emailTaskService;
    @Autowired
    private SiEdiConsumer siEdiConsumer;
    @Autowired
    private FileApi fileApi;
    @Autowired
    private EmailUtil emailUtil;


    @Operation(summary = "创建和提交特种货总接口")
    @PostMapping("/createOrCommitSpc")
    @OperateLog(name = "创建和提交特种货总接口", type = OperateTypeEnum.CREATE)
    public CommonResult<Long> createOrCommitSpc(@Valid @RequestBody CreateOrCommitSpcReqVO createReqVo) {
        createReqVo.setChangeVoyCheck(false);
        Long applyId = specialCargoApplyService.createOrCommitSpc(createReqVo);
        return CommonResult.success(applyId);
    }


    @Operation(summary = "删除特种货申请主信息")
    @PostMapping("/delete/{id}")
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:delete','doc:partnerSpecialApply:delete'})")
    @Parameter(name = "id", description = "编号", required = true)
    @OperateLog(name = "删除特种货申请主信息", type = OperateTypeEnum.DELETE)
    public CommonResult<Void> deleteSpecialCargoApply(@PathVariable("id") Long id) {
        specialCargoApplyService.deleteSpecialCargoApply(id);
        return CommonResult.success();
    }

    @Operation(summary = "获得特种货申请主信息大接口")
    @GetMapping("/getApplyInfo/{id}")
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:preview','doc:partnerSpecialApply:preview'})")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @OperateLog(name = "获得特种货申请主信息大接口", type = OperateTypeEnum.GET)
    public CommonResult<SpecialCargoApplyRespVO> getSpecialCargoApplyInfo(@PathVariable("id") Long id) {
        return CommonResult.success(specialCargoApplyService.getSpecialCargoApplyInfo(id));
    }

    @Operation(summary = "获得特种货申请主信息分页")
    @PostMapping("/page")
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:query','doc:partnerSpecialApply:query'})")
    @OperateLog(name = "获得特种货申请主信息分页", type = OperateTypeEnum.GET)
    @UseResponsePropertyAdvice
    public CommonResult<PageResult<ApplyAndVoyageInfoVO>> getSpecialCargoApplyPage(@Valid @RequestBody SpecialCargoApplyPageReqVO pageVo) {
        PageResult<ApplyAndVoyageInfoVO> results = specialCargoApplyService.getSpecialCargoApplyPage(pageVo);
        return CommonResult.success(results);
    }

    @Operation(summary = "从源数据复制信息")
    @PostMapping("/copySpc")
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:copy','doc:partnerSpecialApply:copy'})")
    @OperateLog(name = "从源数据复制信息", type = OperateTypeEnum.GET)
    public CommonResult<SpecialCargoApplyRespVO> copySpc(@Valid @RequestBody SpecialApplyCommonReqVO originalVo) {
        return CommonResult.success(specialCargoApplyService.copySpc(originalVo));
    }

    @GetMapping("/export")
    @Operation(summary = "excel导出")
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:export','doc:partnerSpecialApply:export'})")
    @OperateLog(name = "excel导出", type = OperateTypeEnum.EXPORT)
    @UseResponsePropertyAdvice
    public void exportExcelTemplate(HttpServletResponse response, SpecialCargoApplyPageReqVO reqVO) throws IOException {
        List<ApplyAndVoyageInfoExportVO> exportList = specialCargoApplyService.getExportList(reqVO);
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("SpecialCargoApply编码导入模板.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "SpecialCargoApply.xls", "模版", ApplyAndVoyageInfoExportVO.class, exportList);

    }

    @Operation(summary = "根据bookingNo获取主信息下的航线和预配箱")
    @PostMapping("/getVoyageCntrInfos")
    @OperateLog(name = "根据bookingNo获取主信息下的航线和预配箱", type = OperateTypeEnum.GET)
    public CommonResult<VoyageRespVO> getVoyageCntrInfos(@RequestBody SpecialCargoVoyageReqVO reqVo) {
        return CommonResult.success(specialCargoApplyService.getSpecialCargoApplyVoyage(reqVo));
    }

    @GetMapping("/sendMessage")
    public CommonResult<Void> sendMessage(@RequestBody SiEdiReqVO vo) throws IOException {
        CommonResult<byte[]> fileBinary = fileApi.getFileBinary(1983834993704570880L);
        DiskFileItem fileItem = new DiskFileItem(
                "file",
                MediaType.MULTIPART_FORM_DATA_VALUE,
                false,
                "组 799@2x",
                fileBinary.getData().length,
                null
        );
        try {
            fileItem.getOutputStream().write(fileBinary.getData());
        } catch (IOException e) {
            throw new IOException("写入文件内容失败", e);
        }
        HashMap<String, Object> templateParams = getStringObjectHashMap();
        String templateCode = "odoRejected";
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        List<MultipartFile> attachments = new ArrayList<>();
        attachments.add(multipartFile);
        emailUtil.spcSendMail("875701950@qq.com", "1432731663@qq.com", templateCode, templateParams, attachments);


        return CommonResult.success();
    }

    private static HashMap<String, Object> getStringObjectHashMap() {
        HashMap<String, Object> templateParams = new HashMap<>(16);
        templateParams.put("emailTitle", "emailTitle");
        templateParams.put("applyTime", "applyTime");
        templateParams.put("bookingNo", "applyDo.getBookingNo()");
        templateParams.put("vslvoy", "fdfdfdfd");
        templateParams.put("polCode", "applyDo.getPolCode()");
        templateParams.put("podCode", "applyDo.getPodCode()");
        templateParams.put("delCode", "applyDo.getDelCode()");
        templateParams.put("rejectReason", "reason");
        templateParams.put("cargoDetails", "notice");
        return templateParams;
    }


    @GetMapping("/getBookingNo")
    @Operation(summary = "获取bookingNo")
    @OperateLog(name = "获取bookingNo", type = OperateTypeEnum.GET)
    public CommonResult<List<String>> getBookingNo() {
        return CommonResult.success(specialCargoApplyService.getBookingNo());
    }

    @Operation(summary = "取消或退回")
    @PostMapping("/cancelApply")
    @Parameter(name = "applyId", description = "主信息ID", required = true)
    @Parameter(name = "backEdit", description = "退回草稿true,取消false", required = true)
    @OperateLog(name = "取消或退回", type = OperateTypeEnum.UPDATE)
    public CommonResult<Boolean> getFilterInfo(@RequestParam("applyId") Long applyId, @RequestParam(value = "backEdit") boolean backEdit) {
        specialCargoApplyService.cancelApply(applyId, backEdit);
        return CommonResult.success(true);
    }

    @PostMapping("/newApply")
    @Operation(summary = "新建特殊货")
    @OperateLog(name = "新建特殊货", type = OperateTypeEnum.CREATE)
    @PreAuthorize("@ss.hasPermission({'doc:specialApply:oogCreate','doc:specialApply:dgCreate','doc:specialApply:flexiCreate','doc:specialApply:odoCreate'," +
            "'doc:partnerSpecialApply:oogCreate','doc:partnerSpecialApply:dgCreate','doc:partnerSpecialApply:flexiCreate','doc:partnerSpecialApply:odoCreate'})")
    public CommonResult<String> newApply(@Valid @RequestBody SpecialApplyCommonReqVO req) {
        return CommonResult.success(specialCargoApplyService.newApply(req));
    }

    @PostMapping("/perCheck")
    @Operation(summary = "提交前检查")
    @OperateLog(name = "提交前检查", type = OperateTypeEnum.GET)
    public CommonResult<String> perCheck(@Valid @RequestBody ApplyAndVoyageInfoVO req) {
        return CommonResult.success(specialCargoApplyService.perCheck(req));
    }

    @GetMapping("/getDgByBookingNo")
    @Operation(summary = "根据bookingNo获取DG信息")
    @OperateLog(name = "根据bookingNo获取DG信息", type = OperateTypeEnum.GET)
    public CommonResult<List<DgByBookingNo>> getDgByBookingNo(@RequestParam("bookingNo") String bookingNo) {
        return CommonResult.success(specialCargoApplyService.getDgByBookingNo(bookingNo));
    }

    @Operation(summary = "检查是否卸货港车船直取")
    @PostMapping("/directTruckPod")
    @Parameter(name = "delCode", description = "目的港", required = true)
    @OperateLog(name = "检查是否卸货港车船直取", type = OperateTypeEnum.GET)
    public CommonResult<Boolean> directTruckPod(@RequestParam("delCode") String delCode) {
        return CommonResult.success(specialCargoApplyService.directTruckPod(delCode));
    }

    @Operation(summary = "合作方根据voyage信息判断是否过境上海")
    @PostMapping("/getPartnerTransitCnsha")
    @OperateLog(name = "合作方根据voyage信息判断是否过境上海", type = OperateTypeEnum.GET)
    public CommonResult<Boolean> getPartnerTransitCnsha(@RequestBody List<SpecialCargoVoyageUpdateReqVO> reqVo) {
        return CommonResult.success(applySaveOrUpdateService.updateTransitCnsha(StringUtils.EMPTY, StringUtils.EMPTY, reqVo));
    }

}
